# 3.12 keep series methods

In web development, especially when working with forms, there are often scenarios where a form is submitted with incomplete or incorrect data. In such cases, it's a good user experience to show the form back to the user with the data they had entered, so they can correct or complete the form without having to fill in everything from scratch. JFinal provides the keep series methods to facilitate this.

# 1. keepPara:

The keepPara method retains the values of form fields when the form is redisplayed:

  • To keep all form fields:

    keepPara();
    
    1
  • To specify which form fields to keep:

    keepPara("nickName", "email", ...);
    
    1

Without any arguments, keepPara() retains all form fields. The kept parameters are returned to the page as String type. However, if you need to maintain the type of a form field, you can do so as follows:

  • To keep the type as Date:

    keepPara(Date.class, "createAt");
    
    1
  • To keep the type as Integer:

    keepPara(Integer.class, "age");
    
    1

The benefit of specifying the type is that, when these kept values are used in view templates (like Enjoy templates), they can be treated as their respective types without any type conversion.

# 2. keepModel and keepBean:

keepModel is used to retain form fields that are prefixed with a modelName:

<input name="blog.title"   value="#(blog.title ??)"/>
<input name="blog.content" value="#(blog.content ??)" />
1
2

In the above HTML form, the fields are prefixed with blog, which corresponds to a model. When the form is submitted, you'd typically use getModel to bind the form data to a Blog model. If the submitted data has errors or is incomplete, you can use keepModel to retain the form values:

keepModel(Blog.class);
1

keepBean works similarly to keepModel, but it's designed for traditional JavaBeans instead of JFinal's Model. However, if a Model class has setter methods (e.g., generated using a code generator), you can also use keepBean for it.

The key difference is that both keepModel and keepBean retain not just the values but also their original types. This means you don't need to specify types explicitly, making it easier to work with form data in the application logic and templates.

In summary, JFinal's keep series methods make it convenient to handle form submissions, especially in scenarios where user input might be incomplete or erroneous. By retaining form data, you enhance the user experience, preventing users from re-entering all data from scratch.

Last Updated: 9/17/2023, 5:50:29 AM